﻿using AutoMapper;
using MediatR;
using ZGLXM.ErrorCode;
using ZGLXM.Infra.Interface;
using ZGLXM.Infra.Repository;
using ZGLXM.Read.Api.Applicantion.Command.RBAC;
using ZGLXM.Read.Api.Dtos;

namespace ZGLXM.Read.Api.Applicantion.Handler.RBAC
{
    public class GetProfessionCommandHandler : IRequestHandler<GetProfessionCommand, ApiResult>
    {
        private readonly IProfessionRepository professionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetProfessionCommandHandler> logger;
        public GetProfessionCommandHandler(IProfessionRepository professionRepository, IMapper mapper, ILogger<GetProfessionCommandHandler> logger)
        {
            this.professionRepository = professionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(GetProfessionCommand request, CancellationToken cancellationToken)
        {
            var professions = await professionRepository.GetAllAsync(x => x.IsDeleted == false);
            var list = from a in professions
                       join b in professions on a.ParentId equals b.ProfessionId into temp
                       from t in temp.DefaultIfEmpty()
                       select new GetProfessionDTO()
                       {
                           ProfessionId = a.ProfessionId,
                           ProfessionName = a.ProfessionName,
                           ParentId = t?.ProfessionId ?? 0,
                           ParentName = t?.ProfessionName ?? string.Empty
                       };
            var professionDtos = mapper.Map<IList<GetProfessionDTO>>(list);
            return ApiResult.OK(professionDtos);
        }
    }
}
